<template> 
  <div class="manager-task-container">
    <!-- 搜索和过滤区域 -->
    <div class="search-filter-section">
      <el-form :inline="true" class="filter-form">
        <!-- 项目号搜索 -->
        <el-form-item label="项目号">
          <el-input
              v-model="searchForm.projectId"
              placeholder="请输入项目号"
              prefix-icon="el-icon-search"
              @keyup.enter.native="handleSearch">
          </el-input>
        </el-form-item>
        
        <!-- 项目名称搜索 -->
        <el-form-item label="项目名称">
          <el-input
              v-model="searchForm.projectName"
              placeholder="请输入项目名"
              prefix-icon="el-icon-search"
              @keyup.enter.native="handleSearch">
          </el-input>
        </el-form-item>

        <!-- 按钮组 -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="main-table-section">
      <el-card>

        <el-table :data="paginatedTableData" style="width: 100%" :stripe="true" :border="true">
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-table :data="props.row.sonData" style="width: 90%; margin-left:40px" :cell-style="cellStyle">
                <el-table-column
                    v-for="(value, index) in sonColumns"
                    :key="index"
                    :label="value.name"
                    :prop="value.propName">
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button v-if="scope.row.taskStatus == '未完成'" @click="dialogVisible = true; taskTimeSub = '';taskSub = scope.row">提交</el-button>
                  </template>
                </el-table-column>
              </el-table>
              
            </template>
          </el-table-column>
          <el-table-column
              v-for="(value, key, index) in parentsCloums"
              :key="index"
              :label="value.name"
              :prop="value.propName">
          </el-table-column>
          <el-table-column
              label="任务数量"
              width="100"
              align="center">
            <template slot-scope="scope">
              <el-tag type="info">
                {{ scope.row.sonData ? scope.row.sonData.length : 0 }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>

        <!-- 添加分页组件 -->
        <div class="pagination-container">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-size="pageSize"
              :total="filteredTableData.length"
              layout="total, prev, pager, next">
          </el-pagination>
        </div>
      </el-card>
    </div>
    <el-dialog
  title="提交工时"
  :visible.sync="dialogVisible"
  width="30%">
  <el-form  label-width="80px">
            <el-form-item label="任务：">
              <span>{{ taskSub.taskName }}</span>
            </el-form-item>
            <el-form-item label="工时">
                <el-input v-model="taskTimeSub"></el-input>
            </el-form-item>
        </el-form>

  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="handleEdit(); dialogVisible = false">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
import http from "@/api/http";
import * as echarts from 'echarts'; // 引入 ECharts
import { getLineChartData } from '@/api'; // 引入获取堆叠折线图数据的接口
import axios from "axios";

export default {
  name: "MemberTask",
  data() {
    return {
      searchForm: {
        projectId: '',
        projectName: ''
      },
      currentPage: 1,
      pageSize: 15,  // 每页显示15条数据

      userName:'',
      taskSub:'',
      taskTimeSub:'',
      dialogVisible: false,
      
      parentsCloums: [ //外层table的表头
        {
          name: "项目号",
          id: "1",
          propName: "projectId",
        }, {
          name: "项目名称",
          id: "2",
          propName: "projectName",
        }, {
          name: "项目状态",
          id: "3",
          propName: "projectStatus",
        }
      ],
      tableData: [], //外层table的数据
      sonColumns: [ //内层table的表头
        {
          name: "任务名",
          id: "1",
          propName: "taskName",
        },
        {
          name: "任务负责人",
          id: "2",
          propName: "memberName",
        },
        {
          name: "任务权重",
          id: "3",
          propName: "taskPercentage",
        },
        {
          name: "任务工时",
          id: "4",
          propName: "workHours",
        },
        {
          name: "任务状态",
          id: "5",
          propName: "taskStatus",
        }
      ]
    }
  },
  computed: {
    filteredTableData() {
      return this.tableData.filter(item => {
        const idMatch = !this.searchForm.projectId || 
          item.projectId.toString().includes(this.searchForm.projectId);
        
        const nameMatch = !this.searchForm.projectName || 
          item.projectName.toLowerCase().includes(this.searchForm.projectName.toLowerCase());
        
        return idMatch && nameMatch;
      });
    },
    paginatedTableData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredTableData.slice(start, end);
    }
  },
  methods: {
    handleSearch() {
      // 搜索时重置页码
      this.currentPage = 1;
    },
    resetSearch() {
      this.searchForm = {
        projectId: '',
        projectName: ''
      };
      this.currentPage = 1;
      this.fetchProjectsAndTask();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },
    handleEdit() {
      // 提交的逻辑
      http.put(`/api/tasks/update/${this.taskSub.taskId}`, null, {
        params: {
          workHours: this.taskTimeSub,
        }})
          .then(res => {
            this.$message.success("任务更新成功");
            this.fetchProjectsAndTask(); // 更新项目和任务列表
          })
          .catch(error => {
            if (error.response && error.response.status === 400) {
              this.$message.error("您没有权限提交该任务");
            } else {
              console.error(`Error updating task ${this.taskSub.taskId}:`, error);
              this.$message.error("任务更新失败");
            }
          });
    },

    
    async fetchProjectsAndTask() {
      try {
        // 获取所有项目的数据
        const projectsResponse = await http.get('/api/tasks/projects');
        const projects = projectsResponse;

        // 使用 Promise.all 并行获取所有项目的任务信息
        const projectsWithTasks = await Promise.all(projects.map(async (project) => {
          try {
            const tasksResponse = await http.get(`/api/tasks/project/${project.projectId}/tasks`);
            const tasks = tasksResponse || [];
            return {
              ...project,
              sonData: tasks,
              showNewTask: false
            };
          } catch (error) {
            console.error(`Error fetching tasks for project ${project.projectId}:`, error);
            return {
              ...project,
              sonData: [],
              showNewTask: false
            };
          }
        }));
        this.tableData = projectsWithTasks;
      } catch (error) {
        console.error('Error fetching projects:', error);
      }
    },
    
    getName(){
      http.get('/api/userinfo')
          .then(res=>{
            this.userName=res.userName;
            console.log('getUSER',this.userName)
            console.log('getUSER',res.userName);
          })
          .catch(error=>{
            console.error('获取用户名失败');
            this.$message.error("获取用户名失败");
          })
    },
    cellStyle(){//根据情况显示背景色
      return 'background:#F3F6FF'
    },
  },
  created() {
    this.fetchProjectsAndTask();
  },
  mounted(){
    // 不再在 mounted 中初始化图表
    // this.initChart(); 
  }
}
</script>

<style scoped>
.manager-task-container {
  padding: 20px;
}

.search-filter-section {
  background: #fff;
  padding: 20px;
  padding-top: 0;
  border-radius: 4px;
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.main-table-section {
  background: #fff;
  border-radius: 4px;
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.new-task-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.new-task-item {
  margin-right: 10px;
  margin-bottom: 10px;
}

.el-tag {
  font-size: 14px;
  padding: 2px 10px;
}

#chart {
  width: 100%;
  height: 400px;
  background: #ffffff;
  border-radius: 10px;
  box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
}
</style>


<!--
<template>
  <div class="shopList">
    
    <el-table :data="tableData" style="width: 100%" >
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-table :data="props.row.sonData" style="width: 90%;margin-left:40px;" :cell-style="cellStyle">
            <el-table-column
                v-for="(value, index) in sonColumns"
                :key="index"
                :label="value.name"
                :prop="value.propName">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button v-if="scope.row.taskStatus == '未完成'" @click="dialogVisible = true; taskTimeSub = '';taskSub = scope.row">提交</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column
          v-for="(value, key, index) in parentsCloums"
          :key="index"
          :label="value.name"
          :prop="value.propName">
      </el-table-column>
    </el-table>
    <el-dialog
  title="提交工时"
  :visible.sync="dialogVisible"
  width="30%">
  <el-form  label-width="80px">
            <el-form-item label="任务：">
              <span>{{ taskSub.taskName }}</span>
            </el-form-item>
            <el-form-item label="工时">
                <el-input v-model="taskTimeSub"></el-input>
            </el-form-item>
        </el-form>

  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="handleEdit(); dialogVisible = false">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
import http from "@/api/http";

export default {
  name: "MemberTask",
  data() {
    return {
      userName:'',
      taskSub:'',
      taskTimeSub:'',
      dialogVisible: false,
      parentsCloums: [ //外层table的表头
        {
          name: "项目号",
          id: "1",
          propName: "projectId",
        }, {
          name: "项目名称",
          id: "2",
          propName: "projectName",
        }, {
          name: "项目状态",
          id: "3",
          propName: "projectStatus",
        }
      ],
      tableData: [], //外层table的数据
      sonColumns: [ //内层table的表头
        {
          name: "任务ID",
          id: "1",
          propName: "taskId",
        },
        {
          name: "任务名",
          id: "2",
          propName: "taskName",
        },
        {
          name: "任务负责人",
          id: "3",
          propName: "memberName",
        },
        {
          name: "任务权重",
          id: "4",
          propName: "taskPercentage",
        },
        {
          name: "任务状态",
          id: "5",
          propName: "taskStatus",
        }
      ]
    }
  },
  methods: {
    handleEdit() {
      // 提交的逻辑
      http.put(`/api/tasks/update/${this.taskSub.taskId}`,null, {
        params: {
          workHours: this.taskTimeSub,
        }})
          .then(res => {
            this.$message.success("任务更新成功");
            this.fetchProjectsAndTask(); // 更新项目和任务列表
          })
          .catch(error => {
            if (error.response && error.response.status === 400) {
              this.$message.error("您没有权限提交该任务");
            } else {
              console.error(`Error updating task ${this.taskSub.taskId}:`, error);
              this.$message.error("任务更新失败");
            }
          });
    },

    async fetchProjectsAndTask() {
      try {
        // 获取所有项目的数据
        const projectsResponse = await http.get('/api/tasks/projects');
        const projects = projectsResponse;

        // 使用 Promise.all 并行获取所有项目的任务信息
        const projectsWithTasks = await Promise.all(projects.map(async (project) => {
          try {
            const tasksResponse = await http.get(`/api/tasks/project/${project.projectId}/tasks`);
            const tasks = tasksResponse || [];
            return {
              ...project,
              sonData: tasks,
              showNewTask: false
            };
          } catch (error) {
            console.error(`Error fetching tasks for project ${project.projectId}:`, error);
            return {
              ...project,
              sonData: [],
              showNewTask: false
            };
          }
        }));
        this.tableData = projectsWithTasks;
      } catch (error) {
        console.error('Error fetching projects:', error);
      }
    },
    getName(){
      http.get('/api/userinfo')
          .then(res=>{
            this.userName=res.userName;
            console.log(res.userName);
          })
          .catch(error=>{
            console.error('获取用户名失败');
            this.$message.error("获取用户名失败");
          })
    },
    cellStyle(){//根据情况显示背景色
        return 'background:#F3F6FF'
      }
  },
  created() {
    this.fetchProjectsAndTask();
  }
}
</script>

<style>
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.new-task-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.new-task-item {
  margin-right: 10px;
  margin-bottom: 10px;
}
.cell-class-name {
  border-color: #868686;
}
</style>

-->